var type = GetQueryString('type');
var orderInfor = GetQueryString('orderInfor');
var useCardsIdList = '';
var addressId = '';
var deliveryType = '';
var payType = '';
var allPrice = '';
var ifClickNo = '';
var useAbleNum = '';
var storeId=null;

$(function () {
    addressId = getItem('addressId');
    if(addressId==null||addressId==undefined||addressId==""){}else{
        $.ajax({
            url:'/user/getByAddressId.json',
            dataType:'json',
            data:{
                token:getItem('token'),
                addressId:addressId,
                companyCode:getItem('companyCode'),
            },
            type:'post',
            success:function (data) {
                if(data.code==1){
                    $('.name').html(data.datas.name);
                    $('.phone').html(data.datas.phone);
                    $('.address_detail').html(data.datas.city + data.datas.detail);
                }
            }
        })
    }

    if(getItem('deliveryType')==null||getItem('deliveryType')==undefined||getItem('deliveryType')==""){
        deliveryType = 2;
        payType = 1;
    }else{
        deliveryType = getItem('deliveryType');
        payType = getItem('payType');
        $('.way').html(decodeURI(getItem('payTypeHtml'))+' '+decodeURI(getItem('deliveryTypeHtml')));
    }
    if(type==1){
        doConfimOrder();
    }else{
        doConfimOrder2();
    }
})



//立即购买
function doConfimOrder() {
    $.ajax({
        url: '/purchaseOrderC/buyRightNow.json',
        dataType: 'json',
        data: {
            token: getItem('token'),
            orderInfor: orderInfor,
            companyCode:getItem('companyCode'),
        },
        type: 'post',
        beforeSend:function(){
            $('<div class="loading2"><span class="mui-spinner"></span></div>').appendTo($('body'));
        },
        success: function (data) {
            $('.loading2').hide();
            if (data.code == 0) {
                // if(data.msg=="尚未设置默认收货地址"){
                //     mui.confirm( '您还没有收获地址，先去先设置一个吧',' ', ['取消', '去设置'], function(e) {
                //         if (e.index == 1) {
                //             window.location.href="add_address2.html";
                //         } else {
                //             window.location.href=history.go(-2);
                //         }
                //     })
                //     return;
                // }
                mui.toast(data.msg);
                return;
            }
            if (data.code == -1) {
                window.location.href = "login.html";
            }
            doData(data);
        }
    })
}

function doData(b) {
    if((deliveryType==1&&payType==1)||(deliveryType==1&&payType==2)){
        var shopAddress = JSON.parse(getItem('shopAddress'));
        $('.user_info').html('联系人<span class="name">'+shopAddress.name+'</span><span class="phone">'+shopAddress.phone+'</span>');
        $('.address_detail').html(shopAddress.detail);
        storeId=shopAddress.id;
       
    }else{
        if(b.addressType==2){
            if(addressId==null||addressId==undefined||addressId==""){
                $('.name').html(b.address.name);
                $('.phone').html(b.address.phone);
                $('.address_detail').html(b.address.city + b.address.detail);
                addressId = b.address.id;
            }else{}
        }else if(b.addressType==1){
            $('.name').html('请填写详细信息');
            $('.phone').html('');
            $('.address_detail').html(b.addressContent);
        }
    }

    for(var k=0;k<b.goodsList.length;k++){
        $('<div class="goods">\n' +
            '<div class="detailBox mui-clearfix">\n' +
            '<div class="goods-img-box">\n' +
            '<img src="'+b.goodsList[k].good.imgUrl.split(',')[0]+'">\n' +
            '</div> <div class="goods-product-box">\n' +
            '<p class="goodsName">'+b.goodsList[k].good.goodName+'</p>\n' +
            '<span class="guige">'+b.goodsList[k].good.propertiesName+'</span>\n' +
            '<span class="price">￥'+b.goodsList[k].good.goodsPrice+'<i>×'+b.goodsList[k].good.num+'</i></span>\n' +
            '</div></div><div class="addServiceBox" id="addServiceBox'+k+'">\n' +
            '</div></div><div class="line"></div>').appendTo($('.goodsBox'))
        for(var i=0;i<b.goodsList[k].addServices.length;i++){
            $('<div class="addService">\n' +
                '<img class="addSelect" src="../phoneImg/goods_pigeon.jpg" alt="">\n' +
                '<div class="warranty">'+b.goodsList[k].addServices[i].name+'</div>\n' +
                '<div class="warranty_price">￥'+b.goodsList[k].addServices[i].price+'</div>\n' +
                '</div>').appendTo($('#addServiceBox'+k+''))
        }
    }

    if(b.useAbleNum!=0){
        $('.count').html(b.useAbleNum+'张可用');
        $('#couponMoney').html(b.allPrice-b.endPrice+'元');
        $('.discount_money').show();
    }else{
        $('.noUse').show();
        $('.count').html(b.useAbleNum+'张可用');
    }
    useAbleNum = b.useAbleNum;

    $('#totalPrice').html('￥'+b.endPrice);
    $('.num').html(b.goodsList.length+'件商品');
    $('#price1').html('商品：'+b.allPrice+'元');
    $('#price2').html('优惠：'+(b.allPrice-b.endPrice)+'元');
    useCardsIdList = b.useCardsIdList;
    allPrice = b.allPrice;
    //优惠券
    doCoupon(b);
    $('#has_discount').html('确定(已优惠'+(b.allPrice-b.endPrice)+'元)')
}


//去结算
function doConfimOrder2() {
    $.ajax({
        url:'/purchaseOrderC/cartsBuy.json',
        dataType:'json',
        data:{
            token:getItem('token'),
            companyCode:getItem('companyCode'),
        },
        type:'post',
        beforeSend:function(){
            $('<div class="loading2"><span class="mui-spinner"></span></div>').appendTo($('body'));
        },
        success:function (data) {
            $('.loading2').hide();
            if(data.code==0){
                mui.toast(data.msg);
                return;
            }
            if(data.code==-1){
                window.location.href="login.html"
            }
            doData(data);
        }
    })
}

//配送及支付方式
$('.dilever_way').click(function () {
    window.location.href="pay_way.html"
})

//优惠券盒子显示
$('.discount').click(function () {
    // if(ifClickNo='true'){
    //     ifClickNo='false';
    // }
    $('#top2,#useCouponBox').show();
    $('#top1,#goodsBox').hide();
})


//优惠券
function doCoupon(a) {
    var useList = a.useAbleList,
        noUseList = a.unUseAbleList,
        timeOutList = a.timeOutList;
    //可用优惠券
    var couponData = useList;
    if(couponData.length==0){
        $('<div class="kong"><img src="../phoneImg/kong.png" alt="暂无数据"></div>').appendTo($('#coupon_box'));
    }else{
        for(var b=0;b<couponData.length;b++){
            $('<div class="coupon mui-clearfix">\n' +
                '<div class="coupon_left">\n' +
                '<div class="decrease_money"><b>￥</b>'+couponData[b].money+'</div>\n' +
                '</div><div class="coupon_right">\n' +
                '<div class="coupon_name">'+couponData[b].name+'</div>\n' +
                '<div class="coupon_time">'+couponData[b].beginTime+'_'+couponData[b].endUseTime+'</div>\n' +
                '<div class="useState"><img cardId="'+couponData[b].id+'" money="'+couponData[b].money+'" ifSelect="true" src="../phoneImg/goods_pigeon.jpg" alt=""></div>\n' +
                '</div></div>').appendTo($('#coupon_box'));
    }


    }
    //不可用优惠券
    var couponData2 = noUseList;
    var couponData3 = timeOutList;
    if(couponData2.length==0&&couponData3.length==0){
        $('<div class="kong"><img src="../phoneImg/kong.png" alt="暂无数据"></div>').appendTo($('#coupon_box2'));
    }else{
        for(var c=0;c<couponData2.length;c++){
            $('<div class="coupon mui-clearfix couponOverdue">\n' +
                '<div class="coupon_left">\n' +
                '<div class="decrease_money"><b>￥</b>'+couponData2[c].money+'</div>\n' +
                '</div><div class="coupon_right">\n' +
                '<div class="coupon_name">'+couponData2[c].name+'</div>\n' +
                '<div class="coupon_time">'+couponData2[c].beginTime+'_'+couponData2[c].endUseTime+'</div>\n' +
                '<div class="useState"><img src="../phoneImg/goods_pigeon.jpg" alt=""></div>\n' +
                '</div></div>').appendTo($('#coupon_box2'));
        }
        for(var d=0;d<couponData3.length;d++){
            $('<div class="coupon mui-clearfix couponOverdue">\n' +
                '<div class="coupon_left">\n' +
                '<div class="decrease_money"><b>￥</b>'+couponData3[d].money+'</div>\n' +
                '</div><div class="coupon_right">\n' +
                '<div class="coupon_name">'+couponData3[d].name+'</div>\n' +
                '<div class="coupon_time">'+couponData3[d].beginTime+'_'+couponData3[d].endUseTime+'</div>\n' +
                '</div></div>').appendTo($('#coupon_box2'));
        }
    }
    var disCountMoey = a.allPrice-a.endPrice;
    var discountSize = useCardsIdList.length;
    mui('.useState').on('tap','img',function () {
        if(ifClickNo=='true'){
            disCountMoey = 0;
            discountSize = 0;
        }else{
            disCountMoey = a.allPrice-a.endPrice;
            discountSize = useCardsIdList.length;
        }
        var couponId = $(this).attr('cardId');
        if($(this).attr('ifSelect')=='true'){
            $(this).attr({'src':'../phoneImg/no_pigeon.jpg','ifSelect':'false'});
            $('.useState img[ifSelect=true]').each(function () {
                disCountMoey+=parseFloat($(this).attr('money'));
            })
            //disCountMoey = disCountMoey - $(this).attr('money');
            discountSize--;
            delCoupon(couponId,useCardsIdList);
        }else{
            $(this).attr({'src':'../phoneImg/goods_pigeon.jpg','ifSelect':'true'});
            $('.useState img[ifSelect=true]').each(function () {
                disCountMoey+=parseFloat($(this).attr('money'));
            })
            //disCountMoey = parseFloat(disCountMoey) + parseFloat($(this).attr('money'));
            discountSize++;
            addCoupon(couponId,useCardsIdList);
        }
        $('#has_discount').html('确定(已优惠'+(disCountMoey)+'元)');
        $('.count').html(useAbleNum+'张可用');
        $('#couponMoney').html(disCountMoey+'元');
        $('#price2').html('优惠：'+disCountMoey+'元');
        $('.discount_money').show();
        $('.noUse').hide();
        $('#totalPrice').html('￥'+(a.allPrice-disCountMoey).toFixed(2));


    })
}

//删除指定优惠券id
function delCoupon(couponId,array) {
    var index = isHasElementOne(array,couponId);
    array.splice(index,1);
}

//返回优惠券下标
function isHasElementOne(arr,value){
    for(var i = 0,vlen = arr.length; i < vlen; i++){
        if(arr[i] == value){
            return i;
        }
    }
    return -1;
}

//添加指定优惠券id
function addCoupon(couponId,array) {
    array.push(couponId);
}

//可用不可用切换
document.getElementById('hasuse').addEventListener('tap',function () {
    $('#coupon_box').hide();
    $('#coupon_box2').show();
    $('#hasuse').addClass('use_act');
    $('#nouse').removeClass('use_act');
})

document.getElementById('nouse').addEventListener('tap',function () {
    $('#coupon_box2').hide();
    $('#coupon_box').show();
    $('#hasuse').removeClass('use_act');
    $('#nouse').addClass('use_act');
})

//优惠券盒子隐藏
document.getElementById('back').addEventListener('tap',function () {
    $('#top2,#useCouponBox').hide();
    $('#top1,#goodsBox').show();
})

//优惠券确定
document.getElementById('has_discount').addEventListener('tap',function () {
    $('#top2,#useCouponBox').hide();
    $('#top1,#goodsBox').show();
})

//不使用优惠券
document.getElementById('no_discount').addEventListener('tap',function () {
    $('#top2,#useCouponBox').hide();
    $('#top1,#goodsBox').show();
    $('.noUse').show();
    $('.count').html(useAbleNum+'张可用');
    $('.discount_money').hide();
    $('#couponMoney').html('0元');
    $('#price2').html('优惠：0元');
    $('#has_discount').html('确定(已优惠0元)');
    $('#totalPrice').html('￥'+allPrice);
    $('.useState img').each(function () {
        $(this).attr({'src':'../phoneImg/no_pigeon.jpg','ifSelect':'false'});
    })
    ifClickNo = 'true';
    useCardsIdList = [];
})

//提交订单
document.getElementById('submit').addEventListener('tap',function () {
    useCardsIdList = useCardsIdList.toString();
    if(type==1){
        //立即购买提交
        $.ajax({
            url:'/purchaseOrderC/submitOrder.json',
            dataType:'json',
            data:{
                token:getItem('token'),
                type:'1',
                orderInfor:orderInfor,
                addressId:addressId,
                userCardsId:useCardsIdList,
                deliveryType:deliveryType,
                payType:payType,
                memo:$('#tips').val(),
                companyCode:getItem('companyCode'),
                storeId:storeId,
            },
            beforeSend: function () {
                $('<div class="loading2"><span class="mui-spinner"></span></div>').appendTo($('body'));
            },
            success:function (data) {
                $('.loading2').hide();
                if(data.code==1){
                    removeItem('addressId');
                    var payMoney = data.payMoney;
                    var code= data.pCode;
                    if((deliveryType==2&&payType==1)||(deliveryType==1&&payType==1)){
                        window.location.href="choosePayWay.html?payMoney="+payMoney+'&code='+code;
                    }else if(deliveryType==1&&payType==2){
                        window.location.href="confirmSuccess.html?payMoney="+payMoney+'&code='+code;
                    }
                }
                if(data.code==0||data.code==3){
                    mui.toast(data.msg);
                    return;
                }
                if(data.code==-1){
                    window.location.href="login.html"
                }
            }
        })
    }else{
        //购物车提交
        $.ajax({
            url:'/purchaseOrderC/submitOrder.json',
            dataType:'json',
            data:{
                token:getItem('token'),
                type:'2',
                addressId:addressId,
                userCardsId:useCardsIdList,
                deliveryType:deliveryType,
                payType:payType,
                memo:$('#tips').val(),
                companyCode:getItem('companyCode'),
            },
            beforeSend: function () {
                $('<div class="loading2"><span class="mui-spinner"></span></div>').appendTo($('body'));
            },
            success:function (data) {
                $('.loading2').hide();
                if(data.code==1){
                    removeItem('addressId');
                    var payMoney = data.payMoney;
                    var code= data.pCode;
                    if((deliveryType==2&&payType==1)||(deliveryType==1&&payType==1)){
                        window.location.href="choosePayWay.html?payMoney="+payMoney+'&code='+code+'&deliverType='+deliveryType+'&payType='+payType;
                    }else if(deliveryType==1&&payType==2){
                        window.location.href="confirmSuccess.html?payMoney="+payMoney+'&code='+code;
                    }
                }
                if(data.code==0||data.code==3){
                    mui.toast(data.msg);
                    return;
                }
                if(data.code==-1){
                    window.location.href="login.html"
                }
            }
        })
    }
})

//地址
document.getElementById('setUrl').addEventListener('tap',function () {
    setItem('setUrl',window.location.href);
})

mui('.mui-scroll-wrapper').scroll({
    deceleration: 0.0005 //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006
});